﻿using System;
using System.Text;
using System.Threading;
using System.Web.UI;
using visinia.SmartEngine;

public partial class Admin_SystemMenu : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        LiteralControl menu = new LiteralControl(Render());
        Controls.Add(menu);
    }

    private string Render()
    {        
        StringBuilder sb = new StringBuilder();
        sb.Append("<ul id=\"system-menu\" >");
        Bind(sb);
        sb.Append("</ul>");
        return sb.ToString();
    }

    private void Bind(StringBuilder sb)
    {
        int index = 0;
        foreach (SystemMenuHeader menueHeader in SystemMenu.GetSystemMenu())
        {
            sb.Append("<li id=\"index_" + index++ + "\" class=\"menu-list\"><a class=\"menu-header\">" + menueHeader.Header.Remove(0, 1) + "</a>");
            sb.Append("<ul>");
            foreach (SystemMenuPage page in menueHeader.Page)
            {
                if (string.Compare(page.Visible, "true", true) != 0)
                    continue;
                bool global = false;
                if (string.IsNullOrEmpty(page.Role))
                    global = true;
                if (Thread.CurrentPrincipal.IsInRole(page.Role) || (Thread.CurrentPrincipal.IsInRole("admin")) || (global))
                {
                    string pagesurl = SystemMenu.CallPage(menueHeader.Header, page.Name);
                    sb.Append("<li class=\"" + page.Name + "\"><a href=\"" + Server.HtmlEncode(pagesurl) + "\" >" + Translate(page.FriendlyName) + "</a></li>");
                }
            }
            sb.Append("</ul>");
            sb.Append("</li>");
        }
    }

    private string Translate(string txt)
    {
        object translation = GetGlobalResourceObject("translation", txt);
        if (translation != null)
            return translation.ToString();
        return string.Format("[{0}]", txt);        
    }
}